//
//  InputAlertView.swift
//  MIFI
//
//  Created by 金嗓子卡卡 on 2019/5/4.
//  Copyright © 2019 NJMifi. All rights reserved.
//

import UIKit
import SVProgressHUD
class InputAlertView: UIScrollView, AlertAnimationViewProtocol {

    var handle : ((String)->())?
    var delayDismiss = false
    private var isShowP = false
    private var title = ""
    private var inputString = ""
    private var contentString = ""
    
    private lazy var contentView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: screenWidth - 80, height: isShowP ? 210 : (contentString.count > 0 ? 180 + 60 : 180)))
        view.center = screenCenter
        view.backgroundColor = colorRGBA(red: 248, green: 248, blue: 248, alpha: 1)
        view.cornerRadius(radius: 5)
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: contentView.width, height: 60))
        label.textColor = blackColor
        label.font = UIFont.boldSystemFont(ofSize: 22)
        label.textAlignment = .center
        label.text = title
        label.backgroundColor = clearColor
        return label
    }()
    
    private lazy var contentLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: titleLabel.bottom, width: contentView.width, height: 50))
        label.textColor = blackColor
        label.font = UIFont.systemFont(ofSize: 18)
        label.textAlignment = .center
        label.text = contentString
        label.backgroundColor = clearColor
        return label
    }()

    private lazy var inputTextF: UITextField = {
        let tf = UITextField(frame: CGRect(x: 8, y: 60, width: contentView.width - 16, height: 50))
        tf.font = UIFont.systemFont(ofSize: 20)
        tf.backgroundColor = clearColor
        tf.textColor = blackColor
        tf.isSecureTextEntry = isShowP
        tf.layer.borderWidth = 0.5
        tf.layer.borderColor = colorRGBA(red: 210, green: 210, blue: 210, alpha: 1).cgColor
        tf.cornerRadius(radius: 5)
        tf.text = inputString
        return tf
    }()

    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: contentView.width / 2, height: 60))
        btn.bottom = contentView.height
        btn.backgroundColor = clearColor
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        btn.setTitle("Cancel", for: .normal)
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        
        let topLine = CALayer()
        topLine.backgroundColor = colorRGBA(red: 210, green: 210, blue: 210, alpha: 1).cgColor
        topLine.frame = CGRect(x: 0, y: 0, width: btn.width, height: 0.5)
        
        let line = CALayer()
        line.backgroundColor = topLine.backgroundColor
        line.frame = CGRect(x: btn.width - 0.25, y: 0, width: 0.25, height: btn.height)
        
        btn.layer.addSublayer(topLine)
        btn.layer.addSublayer(line)
        
        return btn
    }()
    
    private lazy var finishBtn: UIButton = {
        let btn = UIButton(frame: cancelBtn.frame)
        btn.right = contentView.width
        btn.backgroundColor = clearColor
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        btn.setTitle("OK", for: .normal)
        btn.setTitleColor(UIColor.blue, for: .normal)
        btn.addTarget(self, action: #selector(finishAction), for: .touchUpInside)
        
        let topLine = CALayer()
        topLine.backgroundColor = colorRGBA(red: 210, green: 210, blue: 210, alpha: 1).cgColor
        topLine.frame = CGRect(x: 0, y: 0, width: btn.width, height: 0.5)
        
        let line = CALayer()
        line.backgroundColor = topLine.backgroundColor
        line.frame = CGRect(x: 0, y: 0, width: 0.25, height: btn.height)
        
        btn.layer.addSublayer(topLine)
        btn.layer.addSublayer(line)
        
        return btn
    }()
    
    private lazy var showBtn: UIButton = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 140, height: 30))
        btn.bottom = cancelBtn.top
        btn.backgroundColor = clearColor
        btn.setImage(UIImage(named: "icon_normal"), for: .normal)
        btn.setImage(UIImage(named: "icon_selected"), for: .selected)
        btn.setTitle("Show password", for: .normal)
        btn.setTitle("Show password", for: .selected)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btn.setTitleColor(blackColor, for: .normal)
        btn.setTitleColor(blackColor, for: .selected)
        btn.addTarget(self, action: #selector(showAction(sender:)), for: .touchUpInside)
        return btn
    }()
    
    init(input:String,title:String = "Alert",isShowPassword:Bool = false,content:String = "") {
        super.init(frame: .zero)
        isShowP = isShowPassword
        inputString = input
        contentString = content
        self.title = title
        configView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func configView() {
        frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
        backgroundColor = clearColor
        contentSize = screenSize
        isScrollEnabled = false
        
        addSubview(contentView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(inputTextF)
        contentView.addSubview(cancelBtn)
        contentView.addSubview(finishBtn)
        if isShowP {
            contentView.addSubview(showBtn)
        }
        if contentString.count > 0 {
            contentView.addSubview(contentLabel)
            inputTextF.top = contentLabel.bottom + 10
        }
    }
    
    func showAnimation() {
        UIView.animate(withDuration: 0.2) {[weak self] in
            self?.contentView.alpha = 1
        }
    }
    
    func dismissAnimation(finish: @escaping (() -> ())) {
        UIView.animate(withDuration: 0.2, animations: {[weak self] in
            self?.contentView.alpha = 0
        }) { (finished) in
            if finished {
                finish()
            }
        }
    }
    
    @objc private func cancelAction() {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "CloseCustomAlertVC"), object: nil)
    }
    
    @objc private func finishAction() {
        guard !isEmpty(string: inputTextF.text) else {
            SVProgressHUD.showError(withStatus: "Please enter a valid content")
            return
        }
        
        if isShowP {
            guard inputTextF.text!.count >= 8 else {
                SVProgressHUD.showError(withStatus: "Minimum input: 8 characters")
                return
            }
        }
        
        if contentString != "" {
            guard inputTextF.text!.isMacAddress() else {
                SVProgressHUD.showError(withStatus: "Please enter the correct MAC")
                return
            }
        }
        
        if delayDismiss {
            changeAccount(newName: inputTextF.text!)
            return
        }
        if handle != nil {
            handle!(inputTextF.text!)
        }
        
        cancelAction()
    }
    
    @objc private func showAction(sender:UIButton) {
        inputTextF.isSecureTextEntry = sender.isSelected
        sender.isSelected = !sender.isSelected
    }
    
    private func changeAccount(newName:String) {
        guard newName.count > 0 else {
            SVProgressHUD.showError(withStatus: "The field cannot be empty.")
            return
        }
        net_updateAccount(oldA: newName, newA: UserInfoManager.shared().password) {[weak self] (success) in
            if success {
                DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
                    self?.cancelAction()
                })
                UserInfoManager.shared().saveLoginInfo(account: newName, password: UserInfoManager.shared().password, savePassword: true)
            }
            
        }
    }
}
